package cn.zhentao.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 简单API控制器
 * 提供前端需要的基础API接口
 */
@Slf4j
@CrossOrigin(origins = "*")
@RestController
public class SimpleApiController {

    /**
     * 获取搜索历史接口 (简化版本)
     */
    @GetMapping("/ai-tutor/search-history-simple")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getSearchHistorySimple(
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            log.info("获取搜索历史 - 用户ID: {}, 页码: {}, 每页大小: {}", userId, page, size);
            
            // 模拟搜索历史数据
            List<Map<String, Object>> historyList = new ArrayList<>();
            for (int i = 1; i <= Math.min(size, 10); i++) {
                Map<String, Object> history = new HashMap<>();
                history.put("id", (page - 1) * size + i);
                history.put("userId", userId != null ? userId : 1);
                history.put("questionText", "数学题目示例 " + i + "：解方程 " + i + "x + 3 = 7");
                history.put("answer", "x = " + (4.0/i));
                history.put("subject", "数学");
                history.put("createdTime", new Date());
                historyList.add(history);
            }
            
            map.put("code", 200);
            map.put("message", "获取搜索历史成功");
            map.put("data", historyList);
            map.put("total", 50);
            map.put("page", page);
            map.put("size", size);
            
        } catch (Exception e) {
            log.error("获取搜索历史失败", e);
            map.put("code", 500);
            map.put("message", "获取搜索历史失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 拍照搜题接口 (简化版本)
     */
    @PostMapping("/ai-tutor/integrated-search-simple")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> integratedSearchSimple(
            @RequestParam Long userId,
            @RequestParam(required = false) Long sessionId,
            @RequestParam MultipartFile imageFile) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            log.info("开始拍照搜题 - 用户ID: {}, 文件: {}", userId, imageFile.getOriginalFilename());
            
            // 模拟OCR识别
            String ocrResult = "解方程：2x + 3 = 7，求x的值";
            
            // 模拟AI分析
            Map<String, Object> aiAnalysis = new HashMap<>();
            aiAnalysis.put("subject", "数学");
            aiAnalysis.put("questionType", "一元一次方程");
            aiAnalysis.put("analysis", "这是一个简单的一元一次方程问题，需要通过移项来求解。");
            aiAnalysis.put("solution", "步骤1：移项得 2x = 7 - 3 = 4\n步骤2：两边同时除以2得 x = 2");
            aiAnalysis.put("answer", "x = 2");
            aiAnalysis.put("confidence", 0.95);
            
            // 模拟相似题目
            List<Map<String, Object>> similarQuestions = new ArrayList<>();
            Map<String, Object> similar = new HashMap<>();
            similar.put("id", "1");
            similar.put("question", "解方程：3x - 2 = 10");
            similar.put("answer", "x = 4");
            similar.put("explanation", "移项得：3x = 12，所以 x = 4");
            similar.put("difficulty", 2);
            similar.put("subject", "数学");
            similarQuestions.add(similar);
            
            map.put("success", true);
            map.put("message", "搜题成功");
            map.put("questionId", System.currentTimeMillis());
            map.put("sessionId", sessionId != null ? sessionId : System.currentTimeMillis());
            map.put("questionText", ocrResult);
            map.put("ocrResult", ocrResult);
            map.put("aiAnalysis", aiAnalysis);
            map.put("similarQuestions", similarQuestions);
            map.put("processingTime", 1500);
            
        } catch (Exception e) {
            log.error("拍照搜题失败", e);
            map.put("success", false);
            map.put("message", "搜题失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 创建聊天会话接口
     */
    @PostMapping("/ai-chat/sessions")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> createChatSession(@RequestBody Map<String, Object> request) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String sessionName = request.get("sessionName").toString();
            
            log.info("创建聊天会话 - 用户ID: {}, 会话名: {}", userId, sessionName);
            
            Map<String, Object> session = new HashMap<>();
            session.put("id", System.currentTimeMillis());
            session.put("userId", userId);
            session.put("sessionName", sessionName);
            session.put("createdTime", new Date());
            session.put("updatedTime", new Date());
            session.put("messageCount", 0);
            
            map.put("code", 200);
            map.put("message", "会话创建成功");
            map.put("data", session);
            
        } catch (Exception e) {
            log.error("创建聊天会话失败", e);
            map.put("code", 500);
            map.put("message", "创建会话失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 获取聊天会话列表接口
     */
    @GetMapping("/ai-chat/sessions")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getChatSessions(@RequestParam Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            log.info("获取聊天会话列表 - 用户ID: {}", userId);
            
            List<Map<String, Object>> sessions = new ArrayList<>();
            for (int i = 1; i <= 3; i++) {
                Map<String, Object> session = new HashMap<>();
                session.put("id", (long) i);
                session.put("userId", userId);
                session.put("sessionName", "聊天会话 " + i);
                session.put("createdTime", new Date());
                session.put("updatedTime", new Date());
                session.put("messageCount", i * 5);
                sessions.add(session);
            }
            
            map.put("code", 200);
            map.put("message", "获取会话列表成功");
            map.put("data", sessions);
            
        } catch (Exception e) {
            log.error("获取聊天会话列表失败", e);
            map.put("code", 500);
            map.put("message", "获取会话列表失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 发送消息接口
     */
    @PostMapping("/ai-chat/messages")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, Object> request) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            Long sessionId = Long.valueOf(request.get("sessionId").toString());
            String message = request.get("message").toString();
            
            log.info("发送消息 - 用户ID: {}, 会话ID: {}, 消息: {}", userId, sessionId, message);
            
            // 模拟AI回复
            String aiResponse = "我理解您的问题：" + message + "。这是一个很好的问题，让我来为您详细解答...";
            
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("id", System.currentTimeMillis());
            messageData.put("sessionId", sessionId);
            messageData.put("userId", userId);
            messageData.put("message", message);
            messageData.put("response", aiResponse);
            messageData.put("messageType", "text");
            messageData.put("createdTime", new Date());
            
            map.put("code", 200);
            map.put("message", "消息发送成功");
            map.put("data", messageData);
            
        } catch (Exception e) {
            log.error("发送消息失败", e);
            map.put("code", 500);
            map.put("message", "发送消息失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * OCR通用识别接口 (简化版本)
     */
    @PostMapping("/ocr/general/file-simple")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> ocrGeneralSimple(@RequestParam MultipartFile file) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            log.info("OCR通用识别 - 文件: {}", file.getOriginalFilename());
            
            // 模拟OCR识别结果
            String ocrResult = "这是通过OCR识别出的文本内容。\n包含数学公式：2x + 3 = 7\n以及一些中文文字内容。";
            
            Map<String, Object> data = new HashMap<>();
            data.put("ocrResult", ocrResult);
            data.put("fileName", file.getOriginalFilename());
            data.put("processingTime", 800);
            
            map.put("success", true);
            map.put("message", "OCR识别成功");
            map.put("data", data);
            map.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("OCR识别失败", e);
            map.put("success", false);
            map.put("message", "OCR识别失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    /**
     * 获取聊天消息历史接口
     */
    @GetMapping("/ai-chat/messages")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getChatMessages(
            @RequestParam Long sessionId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            log.info("获取聊天消息 - 会话ID: {}, 页码: {}, 每页大小: {}", sessionId, page, size);
            
            List<Map<String, Object>> messages = new ArrayList<>();
            for (int i = 1; i <= Math.min(size, 5); i++) {
                // 用户消息
                Map<String, Object> userMsg = new HashMap<>();
                userMsg.put("id", (long) (i * 2 - 1));
                userMsg.put("sessionId", sessionId);
                userMsg.put("message", "用户问题 " + i);
                userMsg.put("response", "");
                userMsg.put("messageType", "text");
                userMsg.put("createdTime", new Date());
                userMsg.put("isUser", true);
                messages.add(userMsg);
                
                // AI回复
                Map<String, Object> aiMsg = new HashMap<>();
                aiMsg.put("id", (long) (i * 2));
                aiMsg.put("sessionId", sessionId);
                aiMsg.put("message", "");
                aiMsg.put("response", "AI回复 " + i + "：这是对您问题的详细解答...");
                aiMsg.put("messageType", "text");
                aiMsg.put("createdTime", new Date());
                aiMsg.put("isUser", false);
                messages.add(aiMsg);
            }
            
            map.put("code", 200);
            map.put("message", "获取消息成功");
            map.put("data", messages);
            map.put("total", 20);
            map.put("page", page);
            map.put("size", size);
            
        } catch (Exception e) {
            log.error("获取聊天消息失败", e);
            map.put("code", 500);
            map.put("message", "获取消息失败：" + e.getMessage());
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}
